package com.hyzh.pdfview.pdfreader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.TextView;
import android.widget.Toast;

import com.epapyrus.plugpdf.SimpleDocumentReader;
import com.epapyrus.plugpdf.SimpleDocumentReaderListener;
import com.epapyrus.plugpdf.SimpleReaderFactory;
import com.epapyrus.plugpdf.core.PlugPDF;
import com.epapyrus.plugpdf.core.PlugPDFException;
import com.epapyrus.plugpdf.core.viewer.BasePlugPDFDisplay;
import com.epapyrus.plugpdf.core.viewer.DocumentState;
import com.hyzh.pdfview.utils.GetPathFromUri4kitkat;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    //获取权限
    public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
    public static final String DETAULT_FILE = "20160527.pdf";//sample.pdf

    private final int ACTIVITY_CHOOSE_FILE = 1;
    public static final int PERMISSION_CODE = 42042;
    protected File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

    private TextView openDefault;

    private String path = "";
    private SimpleDocumentReader mReader;

    private LocalBroadcastManager localBroadcastManager;
    private MyBroadCastReceiver myBroadCastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        path = downloadDir.getAbsolutePath() + "/" + DETAULT_FILE;
        // init PlugPDF
        try {
            PlugPDF.init(getApplicationContext(),
                    "D9B22DA93HF9GH59ED34BC3F6C227AG878DGE239E478B49B8CH7FBF5");
        } catch (PlugPDFException.InvalidLicense ex) {
            Log.e("PlugPDF", "Invalid license exception", ex);
        }
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        initView();
        initbroadcase();
    }

    public void initView(){
        openDefault = (TextView) findViewById(R.id.open_default);
        openDefault.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.pick_file:
                Log.i("log---------------","pickFile-----------");
                int permissionCheck = ContextCompat.checkSelfPermission(this,
                        READ_EXTERNAL_STORAGE);

                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(
                            this,
                            new String[]{READ_EXTERNAL_STORAGE},
                            PERMISSION_CODE
                    );
                }
                launchPicker();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void launchPicker() {
        Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
        chooseFile.setType("application/pdf");
        startActivityForResult(Intent.createChooser(chooseFile, "Choose a file"), ACTIVITY_CHOOSE_FILE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                launchPicker();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.open_default:
                openDefaultPDF(path);
                //openDefault.setVisibility(View.GONE);
                break;
        }
    }

    public void openDefaultPDF(String path) {
        mReader = SimpleReaderFactory.createSimpleViewer(this, listener);
        mReader.openFile(path, "");
        mReader.setPageDisplayMode(BasePlugPDFDisplay.PageDisplayMode.VERTICAL);
        //mReader.setTitle("Sample");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ACTIVITY_CHOOSE_FILE) {
            if (resultCode == RESULT_OK) {
                //获取文件Uri
                Uri fileUri = data.getData();
                String path = GetPathFromUri4kitkat.getPath(MainActivity.this, fileUri);
                //检测文件是否可用
                String validationMssg = validateFile(path);
                if(validationMssg != null) {
                    Toast toast = Toast.makeText(getApplicationContext(), validationMssg, Toast.LENGTH_LONG);
                    toast.show();
                }
                else {
                    //加载pdfview
                    openDefaultPDF(path);
                    //mReader = SimpleReaderFactory.createSimpleViewer(this, listener);
                    //mReader.openFile(path, "");
                    //mReader.setPageDisplayMode(BasePlugPDFDisplay.PageDisplayMode.VERTICAL);
                }
            }
        }
    }

    /**
     * listener implemented to receive event notifications on completion of PDF document loading on a {@link SimpleDocumentReader}
     */
    private SimpleDocumentReaderListener listener = new SimpleDocumentReaderListener() {

        @Override
        public void onLoadFinish(DocumentState.OPEN state) {
            Log.i("PlugPDF", "[INFO] Open " + state);
        }
    };

    /**
     * 检测文件
     * @param path
     * @return
     */
    private String validateFile(String path) {
        String mssg = null;
        //文件扩展名
        String extension = MimeTypeMap.getFileExtensionFromUrl(path);
        File file = new File(path);
        //文件是否可读
        if (!file.canRead()) {
            mssg = "文件: ".concat(path).concat("\n不可读");
        }
        //检查文件扩展名
        else if (!extension.toLowerCase().equals("pdf")) {
            mssg = "文件: ".concat(path).concat("\n不是PDF文件");
        }
        return mssg;
    }

    /**
     * 初始化本地广播
     */
    public void initbroadcase() {
        myBroadCastReceiver = new MyBroadCastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.hyzh.pdfview.pdfreader");
        localBroadcastManager.registerReceiver(myBroadCastReceiver, filter);
    }

    /**
     * 广播接收数据
     *
     * @author Shire Yin
     *
     */
    public class MyBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            String action = arg1.getAction();
            if (action.equals("com.hyzh.pdfview.pdfreader")) {
                int index = arg1.getIntExtra("index", -1);
                if (index > -1) {
                    mReader.goToPage(index);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        //销毁mReader对象
        if (mReader != null && mReader.getDocument() != null) {
            mReader.save();
            mReader.clear();
        }
        //销毁广播
        if (localBroadcastManager != null && myBroadCastReceiver != null) {
            localBroadcastManager.unregisterReceiver(myBroadCastReceiver);
        }
        super.onDestroy();
    }
}
